package com.mydemo.spring.dynamicroutes.api;

import com.mydemo.spring.dynamicroutes.config.MyRouteConfig;
import com.mydemo.spring.dynamicroutes.entity.MyRoute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @name 路由管理接口
 * @auth DIY
 * @date 2020/10/13 18:17
 **/
@RestController
@RequestMapping("/api/route")
public class RouteApi {

    private final List<MyRoute> routes = new ArrayList<>();

    @Autowired
    MyRouteConfig routeConfig;


    public RouteApi(){
        MyRoute myRoute1 = new MyRoute("route001", "group01", 10, "/route/s1/*", "http://127.0.0.1:8080");
        MyRoute myRoute2 = new MyRoute("route002", "group01", 10, "/route/s1/*", "http://127.0.0.1:8081");
        MyRoute myRoute3 = new MyRoute("route003", "group01", 10, "/route/s1/*", "http://127.0.0.1:8082");
        MyRoute myRoute4 = new MyRoute("route004", "group02", 10, "/route/s2/*", "http://127.0.0.1:8083");
        MyRoute myRoute5 = new MyRoute("route005", "group02", 10, "/route/s2/*", "http://127.0.0.1:8084");
        MyRoute myRoute6 = new MyRoute("route006", "group03", 10, "/route/s3/*", "http://127.0.0.1:8085");
        routes.add(myRoute1);
        routes.add(myRoute2);
        routes.add(myRoute3);
        routes.add(myRoute4);
        routes.add(myRoute5);
        routes.add(myRoute6);
    }


    @RequestMapping("/hello/{name}")
    public String hello(@PathVariable String name){
        return "hello: " + name;
    }




    @RequestMapping("/add/{id}")
    public String addRoute(@PathVariable String id){
        List<MyRoute> myRouteList = routes.stream()
                .filter(route -> route.getRouteId().equals(id))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(myRouteList)){
            return "not found route";
        }
        MyRoute myRoute = myRouteList.get(0);
        routeConfig.addRoutes(myRoute);
        return "addRoute: " + myRoute;
    }

    @RequestMapping("/del/{id}")
    public String delRoute(@PathVariable String id){
        List<MyRoute> myRouteList = routes.stream()
                .filter(route -> route.getRouteId().equals(id))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(myRouteList)){
            return "not found route";
        }
        MyRoute myRoute = myRouteList.get(0);
        routeConfig.delRoutes(myRoute.getRouteId());
        return "delRoute: " + myRoute;
    }






}
